package com.jerei.store.controller;

import com.jerei.store.controller.ex.*;
import com.jerei.store.entity.Address;
import com.jerei.store.entity.User;
import com.jerei.store.service.IUserService;
import com.jerei.store.service.ex.InsertException;
import com.jerei.store.service.ex.UsernameDuplicationException;
import com.jerei.store.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController extends BaseController {




    @Autowired
   private IUserService userService;


    //http://localhost:8080/user/register?username=admin&password=1234&gender=0&phone=139757575

    @RequestMapping("/register")
    public JsonResult<Void> reg(User user){

        userService.register(user);

        return new JsonResult<Void>(OK);
    }

    //http://localhost:8080/user/login?username=admin&password=1234

    @RequestMapping("/login")
    public JsonResult<User> login(Integer checked, String username, String password, HttpSession session,HttpServletResponse response){
        System.err.println("checked="+checked);
        User data= userService.login(username,password);
        if(checked==1){
            data.setPassword(password);
//            Cookie c1=new Cookie("username",username);
//            Session.Cookie
        }
        session.setAttribute("uid",data.getUid());
        session.setAttribute("username",data.getUsername());
        //session.setAttribute("avatar",data.getAvatar());
        return new JsonResult<>(OK,data);
    }

    //自动登录 用request 和response
   // @RequestMapping("/auto")
//    public JsonResult<Void> autoLogin(HttpServletRequest request){
//        Cookie[] cookies=request.getCookies();
//        String username=null;
//        String password=null;
//        if(cookies!=null){
//            for(Cookie cookie:cookies){
//                if(cookie.getName().equals("username")){
//                    username=cookie.getValue();
//                }
//                if(cookie.getName().equals("password")){
//                    password=cookie.getValue();
//                }
//            }
//            System.out.println("从cookie中获取的username和password分别是"+username+","+password);
//            //if(password!=null){
//                return new JsonResult<>(OK);
//            //}
//        }
//        return new JsonResult<>();
//    }

//    @RequestMapping("/auto")
//    public JsonResult<Void> autoLogin(@CookieValue("username")String username,@CookieValue("password") String password){
//        System.out.println("从cookie中获取的username和password分别是"+username+","+password);
//        if(password==null){
//            System.out.println("没有获取到cookie");
//            return new JsonResult<>();
//        }
//        //System.out.println("从cookie中获取的username和password分别是"+username+","+password);
//        return new JsonResult<>(OK);
//    }



    //http://localhost:8080/user/updatePassword?newPassword=123456

    @RequestMapping("/updatePassword")
    public JsonResult<Void> modifiedPassword(String newPassword,String oldPassword,HttpSession session){
        userService.updatePasswordByUid(oldPassword,newPassword,session);
        return new JsonResult<>(OK);
    }


    @RequestMapping("/showInfo")
    public JsonResult<User> foundUser(HttpSession session){
        User user= userService.showUserInfo((Integer)session.getAttribute("uid"));
        return new JsonResult<>(OK,user);
    }

    @RequestMapping("/updateInfo")
    public JsonResult<Void> modifyUser(User user,HttpSession session){
        System.err.println(user);
        userService.changeUserInfo(
                getUidFromSession(session),
                getUsernameFromSession(session),user);
        return new JsonResult<>(OK);
    }

    /**
     * 允许上传的文件大小的上限值  以字节为单位
     */
    private static final long AVATAR_MAX_SIZE = 101*1024;
    /** 允许上传的文件类型集合*/
    private static final List<String> AVATAR_TYPES = new ArrayList<>();

    static {
        AVATAR_TYPES.add("image/jpeg");
        AVATAR_TYPES.add("image/png");
        AVATAR_TYPES.add("image/gif");
        AVATAR_TYPES.add("image/bmp");
    }

    /** 修改头像*/
    @RequestMapping("/avatar/modify")
    public JsonResult<String> changeAvatar(MultipartFile file,HttpSession session){
        //判断文件是否为空
        if(file.isEmpty()){
            //是  抛出FileEmptyEx
            throw new FileEmptyException("上传失败！请选择你要上传的文件");
        }

        //获取文件大小
        long size= file.getSize();
        //判断文件大小是否超出限制
        if(size>AVATAR_MAX_SIZE){
            //是：抛出FileSizeEx
            throw new FileSizeException("上传失败！图片过大，文件不允许超出"+(AVATAR_MAX_SIZE/1024-1)+"KB");
        }

        //获取文件 MIME类型   jpg转换得到的就是jpeg
        String type = file.getContentType();
        //判断文件类型是否不符合所规定的类型
        if (!AVATAR_TYPES.contains(type)){
            throw new FileTypeException("上传失败！图片类型不符合，仅允许上传以下类型"+AVATAR_TYPES);
        }
        //是：则抛出FileTypeEx
        //获取原始文件名(客户端设备中的文件名)
        String originalFilename = file.getOriginalFilename();
        System.err.println("原始文件名："+originalFilename);
        //设置文件保存未知（文件上传到哪里）
        String path = session.getServletContext().getRealPath("upload");
        System.err.println("path:"+path);
        File dir=new File(path);
        if(!dir.exists()){
            dir.mkdirs();
        }
        //重命名文件
        String filename = ""+System.currentTimeMillis()+"2222"+System.nanoTime();
        String suffix=originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFilename=filename+suffix;
        //将文件保存到服务器中
        File avatarFile=new File(dir,newFilename);
       // File avatarFile=new File(path,newFilename);
        try {
            file.transferTo(avatarFile);
        } catch (IOException e) {
            throw new FileUploadIOException("上传失败！文件上传过程中出现错误，请重新上传");
        } catch (IllegalStateException e){
            throw new FileUploadStateException("上传失败！文件状态异常");
        }
        //将保存文件的路径写入到数据库中
        String avatar="/upload/"+newFilename;
        Integer uid=getUidFromSession(session);
        String username=getUsernameFromSession(session);
        userService.changeAvatar(uid,avatar,username);
        //返回响应结果

        return new JsonResult<>(OK,avatar);
    }


















}
